import { defineStore } from "pinia";
import api from '../api/api.js'; // 导入 API 服务

export const useUserStore = defineStore({
    id: "user",
    state: () => ({
        userInfo: null, // 初始化 userInfo 为 null
        userToken: null, // 初始化 userToken 为 null
        tokenExpiration: null, // 用于保存 token 的过期时间
    }),

    actions: {
        changeUserInfo(info) {
            this.userInfo = info; // 更新用户信息
            this.tokenExpiration = Date.now() + 86400000; // 设置过期时间为当前时间 + 1天（86400000毫秒）
            this.saveUserInfoToLocalStorage(); // 保存用户信息到本地存储
        },

        changeUserName(name) {
            this.userInfo.username = name; // 更新用户名
            this.saveUserInfoToLocalStorage(); // 重新保存
        },

        changeUserEmail(email) {
            this.loadUserInfoFromLocalStorage();
            this.userInfo.email = email; // 更新用户邮箱
            this.saveUserInfoToLocalStorage(); // 重新保存
        },

        cartch() {
            this.userInfo = {}; // 清空用户信息
            this.userToken = null; // 清空用户 token
            this.tokenExpiration = null; // 清空过期时间
            this.saveUserInfoToLocalStorage();
            return true;
        },

        async fetchUserInfo(data, log) {
            this.response = null;

            try {
                if (log) {
                    this.response = await api.post('/user/login', data);
                } else {
                    this.response = await api.post('/user/signin', data);
                }

                if (this.response.data.code === 0) {
                    this.userInfo = this.response.data.data.user_info;
                    this.userToken = this.response.data.data.access_token;
                    this.tokenExpiration = Date.now() + 86400000; // 设置过期时间
                    this.saveUserInfoToLocalStorage();
                    return true; // 表示成功
                } else {
                    return false; // 失败
                }
            } catch (error) {
                return false; // 处理错误
            }
        },

        saveUserInfoToLocalStorage() {
            localStorage.setItem('userInfo', JSON.stringify(this.userInfo));
            localStorage.setItem('userToken', JSON.stringify(this.userToken));
            localStorage.setItem('tokenExpiration', JSON.stringify(this.tokenExpiration)); // 保存过期时间
        },

        loadUserInfoFromLocalStorage() {
            const userInfo = localStorage.getItem('userInfo');
            const userToken = localStorage.getItem('userToken');
            const tokenExpiration = localStorage.getItem('tokenExpiration');

            if (userInfo && userToken && tokenExpiration) {
                const expirationTime = JSON.parse(tokenExpiration);
                if (Date.now() < expirationTime) { // 检查过期
                    this.userInfo = JSON.parse(userInfo);
                    this.userToken = JSON.parse(userToken);
                } else {
                    this.clearUserInfo(); // 清除过期的信息
                }
            } else {
                this.userInfo = {}; // 设置为游客
            }
        },

        clearUserInfo() {
            this.userInfo = null;
            this.userToken = null;
            this.tokenExpiration = null;

            localStorage.removeItem('userInfo'); // 清除本地存储
            localStorage.removeItem('userToken');
            localStorage.removeItem('tokenExpiration');
        },
    },

    getters: {
        fullName(state) {
            return `${state.userInfo.firstName} ${state.userInfo.lastName}`;
        },
    },
});
